#include "globalapplication.h"
#include <QWidget>
#include "log.h"
#include <semaphore.h>
#include <pthread.h>
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QTextCodec>
#endif
#include <QTranslator>
#include <QMessageBox>
#include <QDir>
#include "DesktopTimer.h"
#include "config/AppConfig.h"
#include "utils/FontUnit.h"
#include "globalhotkey.h"
#include "ConfigService.h"
#include "SoundService.h"

// 抑制 FFmpeg 音频解码警告（mp3float timestamp 问题）
extern "C" {
#ifdef Q_OS_WIN
    #include <cstdlib>
#endif
}

/**
 * @brief 初始化应用程序属性
 */
void initializeApplicationAttributes()
{
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
    // 启用高DPI缩放 (Qt 6 中默认启用)
    QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
    
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
    // 设置高DPI缩放因子舍入策略
    QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
        Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
}

/**
 * @brief 初始化文本编码
 */
void initializeTextCodec()
{
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
    #if (QT_VERSION <= QT_VERSION_CHECK(5, 0, 0))
        #if _MSC_VER
            QTextCodec *codec = QTextCodec::codecForName("GBK");
        #else
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");
        #endif
        QTextCodec::setCodecForLocale(codec);
        QTextCodec::setCodecForCStrings(codec);
        QTextCodec::setCodecForTr(codec);
    #else
        QTextCodec *codec = QTextCodec::codecForName("UTF-8");
        QTextCodec::setCodecForLocale(codec);
    #endif
#else
    // Qt 6: UTF-8 is default, no codec setup needed
#endif
}

/**
 * @brief 初始化日志系统
 */
void initializeLogger()
{
    qDebug() << "=== initializeLogger START ===";
    qDebug() << "Current path:" << QDir::currentPath();
    
    // 在运行时创建日志配置，避免静态初始化顺序问题
    static Logging::TimeConfigInfo logConfig;
    logConfig.strFilePath = QDir::currentPath() + "/log/";
    logConfig.eBackupType = Logging::BACKUP_BY_DAY;
    logConfig.eLogLevel = Logging::TRACE;
    logConfig.iMaxTotalFileBytes = 50 * 1024 * 1024;
    logConfig.fRecyclePercent = 0.2;
    logConfig.strSuffix = ".log";
    logConfig.iCode = LOG1;
    
    qDebug() << "Log config - Path:" << logConfig.strFilePath << "Code:" << logConfig.iCode;
    
    qDebug() << "Adding logger...";
    Logging::ErrorCode code = LogManager::instance()->addLogger(&logConfig);
    qDebug() << "Add logger result:" << code;
    
    if (code != Logging::ERROR_NONE) {
        qWarning() << "Failed to add logger, error code:" << code;
        return;
    }
    
    qDebug() << "Getting logger for LOG1...";
    Logger* logger = LogManager::instance()->logger(LOG1);
    qDebug() << "Logger pointer:" << logger;
    
    if (logger) {
        qDebug() << "Enabling debug output...";
        logger->enableDebugOutput(Logging::INFO);
        qDebug() << "Calling logInfo...";
        logInfo("========== DesktopTimer 应用启动 ==========");
        qDebug() << "logInfo called successfully";
    } else {
        qWarning() << "Failed to get logger for LOG1";
    }
    
    qDebug() << "=== initializeLogger END ===";
}

/**
 * @brief 加载翻译文件
 * @param app 应用程序对象
 * @return 是否加载成功
 */
bool loadTranslation(QApplication& app)
{
    QTranslator* translator = new QTranslator(&app);
    if (translator->load(":/translation/language_zh_cn.qm")) {
        app.installTranslator(translator);
        logInfo("成功加载中文翻译文件");
        return true;
    } else {
        logWarning("加载翻译文件失败，使用默认语言");
        delete translator;
        return false;
    }
}

/**
 * @brief 初始化应用程序配置
 */
void initializeAppConfig()
{
    AppConfig& config = AppConfig::getInstance();
    config.setEncryptionEnabled(false);
    logInfo("应用配置已初始化");
}

/**
 * @brief 设置全局字体
 * @param app 应用程序对象
 */
void setupGlobalFont(QApplication& app)
{
    try {
        AppConfig& config = AppConfig::getInstance();
        QFont font = config.getFont();
        
        // 设置应用程序全局字体
        app.setFont(font);
        
        // 设置FontUnit单例
        FontUnit::instance().setFamily(font.family());
        FontUnit::instance().setPointSize(font.pointSize());
        FontUnit::instance().setBold(font.bold());
        
        logInfo("全局字体设置完成: " << font.family() << ", " << font.pointSize() << "pt");
    } catch (const std::exception& e) {
        logError("设置全局字体时异常: " << e.what());
    }
}

int main(int argc, char *argv[])
{
    qDebug() << "=== main START ===";
    
    // 抑制 FFmpeg 音频解码警告（必须在任何 QMediaPlayer 使用前设置）
#ifdef Q_OS_WIN
    _putenv_s("AV_LOG_FORCE_NOCOLOR", "1");
    _putenv_s("AV_LOG_LEVEL", "32");  // AV_LOG_ERROR = 16, AV_LOG_WARNING = 24, AV_LOG_INFO = 32
#else
    setenv("AV_LOG_FORCE_NOCOLOR", "1", 1);
    setenv("AV_LOG_LEVEL", "32", 1);
#endif
    
    // 初始化应用程序属性
    qDebug() << "Initializing application attributes...";
    initializeApplicationAttributes();

    // 创建全局应用程序对象
    qDebug() << "Creating GlobalApplication...";
    GlobalApplication app(argc, argv);
    
    // 初始化文本编码（必须在日志之前，因为日志可能需要编码支持）
    qDebug() << "Initializing text codec...";
    initializeTextCodec();

    // 初始化日志系统（必须在使用任何log宏之前）
    qDebug() << "Initializing logger...";
    initializeLogger();

    // 检查是否已有实例在运行
    if (app.isInstanceRunning()) {
        logWarning("检测到已有实例正在运行，程序即将退出");
        QMessageBox::warning(
            nullptr,
            "DesktopTimer",
            "程序已经在运行中！\n请在系统托盘中查找。",
            QMessageBox::Ok
        );
        return 0;  // 退出当前实例
    }

    // 加载翻译文件
    loadTranslation(app);

    // 设置应用程序图标
    QIcon appIcon(":/resource/ico/DesktopTimer.ico");
    app.setWindowIcon(appIcon);
    logInfo("应用程序图标已设置");

    // 初始化应用配置
    initializeAppConfig();

    // 应用全局声音设置（静音/音量/嘀嗒）
    {
        auto &cfg = ConfigService::instance();
        auto &snd = SoundService::instance();
        snd.setMuted(cfg.getGlobalMuted());
        snd.setVolume(cfg.getGlobalVolume());
        if (cfg.getTickEnable()) {
            snd.setTickInterval(cfg.getTickIntervalMs());
            int vol = cfg.getGlobalVolume();
            snd.startTickSound(vol > 0 ? qMax(10, vol/3) : 10);
        }
    }
    // 设置全局字体
    setupGlobalFont(app);

    // 创建并显示主窗口
    DesktopTimer* desktop = nullptr;
    try {
        desktop = new DesktopTimer();
        desktop->show();
        logInfo("主窗口创建成功");
    } catch (const std::exception& e) {
        logError("创建主窗口时异常: " << e.what());
        QMessageBox::critical(
            nullptr,
            "错误",
            QString("启动应用程序失败: %1").arg(e.what()),
            QMessageBox::Ok
        );
        return -1;
    } catch (...) {
        logError("创建主窗口时发生未知异常");
        QMessageBox::critical(
            nullptr,
            "错误",
            "启动应用程序失败：未知错误",
            QMessageBox::Ok
        );
        return -1;
    }

    // 注册全局热键：Ctrl+Alt+S 截图，Alt+Shift+L 幽灵模式
    if (desktop) {
        GlobalHotkeyManager* hotkeyMgr = new GlobalHotkeyManager(&app);
        // 使用老式 SIGNAL/SLOT 连接到私有槽
        QObject::connect(hotkeyMgr, SIGNAL(screenshotHotkeyPressed()), desktop, SLOT(startScreenshot()));
        QObject::connect(hotkeyMgr, SIGNAL(ghostModeHotkeyPressed()), desktop, SLOT(togglePin()));
        bool ok1 = hotkeyMgr->registerScreenshotHotkey();
        bool ok2 = hotkeyMgr->registerGhostModeHotkey();
        if (!ok1) logWarning("注册 Ctrl+Alt+S 截图热键失败");
        if (!ok2) logWarning("注册 Alt+Shift+L 幽灵模式热键失败");
    }

    int result = app.exec();
    
    // 清理资源
    if (desktop) {
        delete desktop;
        desktop = nullptr;
    }
    
    logInfo("========== DesktopTimer 应用退出 ==========");
    return result;
}
